package com.ruiben.mall.impl;

import com.ruiben.mall.ICartService;
import com.ruiben.mall.mapper.UserCartMapper;
import com.ruiben.mall.pojo.UserCart;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private UserCartMapper userCartMapper;

    @Autowired
    private Sid sid;

    @Override
    public boolean addProductToCart(UserCart cart) {
        cart.setId(sid.nextShort());
        return userCartMapper.insert(cart) > 0;
    }

    @Override
    public boolean delProductForCart(String[] ids) {
        List<String> strings = Arrays.asList(ids);
        int i = userCartMapper.batchDeleteCart(strings);
        return i>0;
    }

    @Override
    public boolean updateNumForCart(String id, Integer num) {
        UserCart userCart = new UserCart();
        userCart.setId(id);
        userCart.setProductnum(num);
        int i = userCartMapper.updateByPrimaryKeySelective(userCart);
        return i>0;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<UserCart> getCartList(String userId) {
//        Example example = new Example(UserCart.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("userid", userId);
        return userCartMapper.getCartList(userId);
    }


    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public UserCart getCartInfo(String cartId) {
//        Example example = new Example(UserCart.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("userid", userId);
        return userCartMapper.getCartInfo(cartId);
    }

    /**
     * 检查商品在购物车是否存在
     * @param productId
     * @return
     */
    @Override
    public List<UserCart> isExistProductForCart(String productId) {
        Example example = new Example(UserCart.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productid",productId);
        List<UserCart> userCarts = userCartMapper.selectByExample(example);
        return userCarts;
    }


    /**
     * 更新购物车
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean updateCart(UserCart cart) {
        int i = userCartMapper.updateByPrimaryKeySelective(cart);
        return i>0;
    }
}
